package com.glodon.utils.service;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glodon.spring.enty.User;
import com.glodon.spring.service.UserService;

@Service
public class MyShiro extends AuthorizingRealm{

	/**
	 * 日志管理
	 */
	private Logger logger = LoggerFactory.getLogger(MyShiro.class);

	//依赖注入
	@Autowired
	private UserService userService;

	//权限认证
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		logger.info("jinru");
		String username = principalCollection.getPrimaryPrincipal().toString();
		SimpleAuthorizationInfo info  = new SimpleAuthorizationInfo();
		logger.info("username", username);
		String per = userService.getPermissiin(username);
		Set<String> set = new HashSet<>();
		set.add(per);
		String role = userService.getRole(username);
		Set<String> rol = new HashSet<>();
		rol.add(role);
		logger.info(role+"------------------------");
		info.setRoles(rol);
		info.setStringPermissions(set);
		return info;
	}

	//登录认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		logger.info("首先进入");
		String username = authenticationToken.getPrincipal().toString();
		String password = new String((char[])authenticationToken.getCredentials());
		logger.info("登录username：{}，password：{}",username, password);
		User user  = new User();
		user.setName(username);
		user.setPassword(password);
		User us = userService.sele(user);
		if(us!=null){
			AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getName(),user.getPassword(), getName()) ;

			return authenticationInfo ;
		}else{
			return null;
		}

	}

}
